package com.light.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.pojo.ESPojo;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.gulimall.product.dao.*;
import com.light.gulimall.product.dto.AttrDTO;
import com.light.gulimall.product.dto.UpdateSpuDTO;
import com.light.gulimall.product.entity.*;
import com.light.gulimall.product.service.AttrService;
import com.light.gulimall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
@Transactional(rollbackFor = Exception.class)
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private ProductAttrValueDao productAttrValueDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 获取分类规格参数
     *
     * @param params    查询条件
     * @param catelogId 所属分类id,pms_category 主键id
     * @param attrType  0-销售属性 1-基本属性
     * @return 分页查询结果
     */
    @Override
    public PageUtils getBaseList(Map<String, Object> params, Long catelogId, Long attrType) {
        //组装条件
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //attr_type 0-销售属性 1-基本属性
        queryWrapper.eq("attr_type", attrType);
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        Object key = params.get("key");
        if (key != null) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        //进行分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //处理中间表结果，组装返回
        List<AttrEntity> records = page.getRecords();
        ArrayList<AttrVO> attrVOS = new ArrayList<>();
        for (AttrEntity record : records) {
            AttrVO attrVO = new AttrVO();
            BeanUtils.copyProperties(record, attrVO);
            QueryWrapper<CategoryEntity> categoryEntityQueryWrapper = new QueryWrapper<>();
            categoryEntityQueryWrapper.eq("cat_id", record.getCatelogId());
            CategoryEntity categoryEntity = categoryDao.selectOne(categoryEntityQueryWrapper);
            if (categoryEntity != null) {
                //填充所属分类名字
                attrVO.setCatelogName(categoryEntity.getName());
            }
            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
            attrAttrgroupRelationEntityQueryWrapper.eq("attr_id", record.getAttrId());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(attrAttrgroupRelationEntityQueryWrapper);
            if (attrAttrgroupRelationEntity != null) {
                QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
                attrGroupEntityQueryWrapper.eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(attrGroupEntityQueryWrapper);
                if (attrGroupEntity != null) {
                    //填充所属分组名字
                    attrVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            attrVOS.add(attrVO);
        }
        pageUtils.setList(attrVOS);
        return pageUtils;
    }

    @Override
    public void save(AttrDTO attr) {
        //保存pms_attr 表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        attrDao.insert(attrEntity);

        //保存pms_attr_attrgroup_relation 表
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attrEntity.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationDao.insert(relationEntity);

    }

    /**
     * 根据pms_attr主键id，查询信息
     *
     * @param attrId pms_attr 主键ID
     * @return 查询到的信息
     */
    @Override
    public AttrVO getInfoById(Long attrId) {
        //查询pms_attr表
        AttrEntity attrEntity = this.getById(attrId);
        AttrVO attrVO = new AttrVO();
        BeanUtils.copyProperties(attrEntity, attrVO);
        //查询pms_attr_attrgroup_relation 得到  attrGroupId
        QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
        attrAttrgroupRelationEntityQueryWrapper.eq("attr_id", attrId);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(attrAttrgroupRelationEntityQueryWrapper);
        if (attrAttrgroupRelationEntity != null) {
            attrVO.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
        }

        //设置catelogId
        Long catelogId = attrEntity.getCatelogId();
        attrVO.setCatelogId(catelogId);

        List<AttrGroupEntity> parentCategories = attrGroupDao.findParentCategories(catelogId);
        // 筛选出 catelogId 并转换为 Long 类型的 List，并按升序排序
        List<Long> catelogIdList = parentCategories.stream()
                .map(AttrGroupEntity::getCatelogId)
                .sorted()
                .collect(Collectors.toList());
        //设置catelogPath
        attrVO.setCatelogPath(catelogIdList);
        return attrVO;
    }

    /**
     * 修改pms_attr 和 pms_attr_attrgroup_relation表
     *
     * @param dto 前端传递修改信息
     */
    @Override
    public void modifyById(AttrDTO dto) {
        //修改pms_attr
        this.updateById(dto);
        //pms_attr_attrgroup_relation表 根据attr_id修改
        QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
        attrAttrgroupRelationEntityQueryWrapper.eq("attr_id", dto.getAttrId());
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        BeanUtils.copyProperties(dto, attrAttrgroupRelationEntity);
        attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, attrAttrgroupRelationEntityQueryWrapper);
    }

    /**
     * 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
     *
     * @param params
     * @param attrgroupId pms_attr_group 属性分组表 主键id
     * @return 分页信息
     */
    @Override
    public PageUtils getNoattrRelation(Map<String, Object> params, Long attrgroupId) {
        //查出pms_attr_group中的catelog_id
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        if (null == attrGroupEntity) {
            return null;
        }
        Long catelogId = attrGroupEntity.getCatelogId();
        //查询pms_attr_group中除了自身attr_group_id外其他的数据的attr_group_id
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
        attrGroupEntityQueryWrapper.eq("catelog_id", catelogId);
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(attrGroupEntityQueryWrapper);
        if (CollectionUtils.isEmpty(groupEntities)) {
            return null;
        }
        List<Long> attrGroupIds = groupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        //根据attrGroupIds查询pms_attr_attrgroup_relation的attr_id
        QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
        attrAttrgroupRelationEntityQueryWrapper.in("attr_group_id", attrGroupIds);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(attrAttrgroupRelationEntityQueryWrapper);
        if (CollectionUtils.isEmpty(attrAttrgroupRelationEntities)) {
            return null;
        }
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        //用attrIds查询pms_attr 封装返回数据
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //只查询基本属性
        queryWrapper.in("catelog_id", catelogId).eq("attr_type", 1).notIn("attr_id", attrIds);
        String key = params.get("key").toString();
        if (!StringUtils.isBlank(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 修改商品规格
     *
     * @param spuId spu主键id
     * @param dto   前端传递信息
     * @return 是否修改成功
     */
    @Override
    public void updateSpu(Long spuId, List<UpdateSpuDTO> dto) {
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueDao.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        if (!CollectionUtils.isEmpty(attrValueEntities)) {
            ArrayList<ProductAttrValueEntity> productAttrValueEntities = new ArrayList<>();
            for (int i = 0; i < dto.size(); i++) {
                UpdateSpuDTO updateSpuDTO = dto.get(i);
                ProductAttrValueEntity attrValueEntity = attrValueEntities.get(i);
                // 将 updateSpuDTO 的属性复制到 attrValueEntity 中
                BeanUtils.copyProperties(updateSpuDTO, attrValueEntity);
                productAttrValueEntities.add(attrValueEntity);
            }

            productAttrValueDao.updateById(productAttrValueEntities);
        }
    }


    /**
     * 获取spu规格
     * @param spuId spu主键id
     * @return 查询结果
     */
    @Override
    public List<ProductAttrValueEntity> getBaseListForSpu(Long spuId) {
        return productAttrValueDao.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }


}